<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      body {
        margin-top: 400px;
      }

      .stage {
        perspective: 700px;
      }

      .unit {
        width: 100%;
        height: 100%;
        position: relative;
        transform-style: preserve-3d;
      }

      .grid {
        position: absolute;
        width: 60px;
        height: 80px;
        opacity: 0.5;
        top: 50%;
        left: 50%;
        margin-top: -40px;
        margin-left: -30px;
      }
    </style>
  </head>

  <body>
    <div class="stage">
      <div class="unit"></div>
    </div>
    <script>
      const oUnit = document.querySelector(".unit");
      // 每层需要的元素数量
      const levelNum = [12, 10, 8, 6, 4, 1];

      for (let i = 0; i < levelNum.length - 1; i++) {
        set(i, levelNum[i]);
        if (i === 0) continue; // 已经创建就继续
        set(-i, levelNum[i]);
      }
      function set(floor, num) {
        const fragment = document.createDocumentFragment();
        for (let i = 0; i < 10; i++) {
          const div = document.createElement("div");
          div.className = "grid";
          div.style.cssText = `
          transform: rotateY(${(360 / num) * i}deg) rotateX(${
            floor * 18
          }deg) translateZ(300px);
          background-color: ${rgb(0.8)};
        `;
          fragment.appendChild(div);
        }
        oUnit.appendChild(fragment);
      }

      document.onmousemove = function (ev) {
        oUnit.style.cssText = `
          transform: rotateY(${ev.clientX}deg) rotateX(${ev.clientY}deg);
        `;
      };

      function rgb(alpha) {
        //rgb颜色随机
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        var rgba = `rgba(${r}, ${g}, ${b}, ${alpha || 1})`;
        return rgba;
      }
      function color16() {
        //十六进制颜色随机
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        var color = "#" + r.toString(16) + g.toString(16) + b.toString(16);
        return color;
      }
    </script>
  </body>
</html>
